package cmd

import (
	"eSymCounter/config"
	"eSymCounter/userspace"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/spf13/cobra"
)

func init() {
	soCmd.Flags().StringVarP(&config.ElfPath, "bin", "b", "", "elf file path")
	soCmd.Flags().Uint32VarP(&config.Pid, "pid", "p", 0, "if pid is 0 then we target all pids")
	soCmd.Flags().StringVarP(&config.SoPath, "so", "s", "", "shared object file path")
	soCmd.Flags().StringVarP(&config.OutputFile, "output", "o", "", "output file path, default is stdout")

	soCmd.MarkFlagRequired("so")

	rootCmd.AddCommand(soCmd)
}

var soCmd = &cobra.Command{
	Use:   "so",
	Short: "Count the number of symbol calls in the shared object file",
	Run: func(cmd *cobra.Command, args []string) {
		if config.Pid == 0 {
			log.Println("target pid == 0. It means that eSymCounter will capture all events.")
		}

		stopper := make(chan os.Signal, 1)
		signal.Notify(stopper, os.Interrupt, syscall.SIGTERM)

		ebpfstopper := make(chan struct{}, 1)
		go userspace.RunSo(ebpfstopper)
		<-stopper
		ebpfstopper <- struct{}{}
		for config.BpfProgsNum.Load() > 0 {
			time.Sleep(1 * time.Second)
		}
		time.Sleep(1 * time.Second)
		log.Print("eSymCounter exit")
	},
}
